<?php
declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Library\Common;
use App\Model\data\CurrentShopData;
use App\Model\data\CurrentUserData;
use App\Service\FlyCouponService;
use Hyperf\DbConnection\Db;
use Hyperf\Validation\Rule;
use Hyperf\Di\Annotation\Inject;
use Swoole\Exception;

class ShopCouponController extends  AbstractController
{
    /**
     * @Inject
     * @var FlyCouponService
     */
    private  $FlyCouponService;


//    店铺优惠券列表
    public function list()
    {
        $params = $this->request->all();
        $shop_info =  CurrentShopData::getData();
        $list = $this->paginate($this->FlyCouponService->index($params,intval($shop_info->id)));
        return $this->jsonResponse->success($list,'优惠券列表');
    }

    //    商品用户可用优惠券列表
    public function usable_coupon()
    {
        $params = $this->request->inputs(['use_product_type','shop_id','product_ids']);
        $this->validation(
            $params,
            [
                'shop_id'=>[
                    'required',
                    'integer',
                    Rule::exists('fly_shop','id')
                ],
                'use_product_type' => [
                    'required','integer','min:1','max:2',
                ],
                'product_ids' => [
                    'required','array','min:1',
                ],
                'product_ids.*' => [
                    'required','integer','min:1',
                    Rule::exists('fly_product','id')
                        ->where('check_status','1')
                        ->where('is_show','1')
                        ->where('type',$params['use_product_type'])
                ],
            ],
            );
        $user_info =  CurrentUserData::getData();
        $list = $this->paginate($this->FlyCouponService->products_usable_coupon($params['product_ids'],$params['use_product_type'],intval($user_info->id),intval($params['shop_id'])));
        return $this->jsonResponse->success($list,'已领取优惠券列表');
    }

    //    用户全部优惠券列表
    public function user_coupon()
    {
        $params = $this->request->inputs(['is_used','type']);
        $this->validation(
            $params,
            [
                'is_used'=>[
                    'required',
                    'boolean',
                ],
                'type'=>[
                    'required',
                    'integer',
                    'min:1',
                    'max:2',
                ]
            ],
        );
        $user_info =  CurrentUserData::getData();
        $list = $this->paginate($this->FlyCouponService->user_coupon(intval($user_info->id),intval($params['is_used']),intval($params['type'])));
        return $this->jsonResponse->success($list,'已领取优惠券列表');
    }

//    用户领取接口 需要登录
    public function receive()
    {
        $coupon_id = $this->request->input('coupon_id',0);
        $this->validation(
            [
                'coupon_id'=>$coupon_id
            ],
            [
                'coupon_id'=>[
                    'required',
                    'integer',
                    Rule::exists('fly_coupon','id')->where(function ($query){
                        $time = Common::date_time(2);
                        $query->where('status','1')
                            ->where('use_begin_time','<',$time)
                            ->where('use_end_time','>',$time);
                    })
                ]
            ],
        );
        $user_info =  CurrentUserData::getData();
        $res = $this->FlyCouponService->receive_coupon(intval($coupon_id),intval($user_info->id));
        if($res==true){
            return $this->jsonResponse->error($res,'领取成功');
        }else{
            return $this->jsonResponse->success($res,'领取失败或已领取上限');
        }
    }

//    查看用户可用优惠券列表
    public function public_list()
    {
        $params = $this->request->inputs(['shop_id','product_id']);
        $this->validation($params,[
                'shop_id'=>[
                    'required','integer','min:1',
                ],
                'product_id'=>
                    'integer',
                    Rule::exists('fly_product','id')
                        ->where('check_status','1')
                        ->where('is_show','1')
            ],
        );
        $list = $this->paginate($this->FlyCouponService->index($params,intval($params['shop_id']),2));
        return $this->jsonResponse->success($list,'优惠券列表');
    }

    public function add()
    {
        $shop =  CurrentShopData::getData();
        $params = $this->request->all();
        $checkKey= [
            'use_begin_time' => 'required|date_format:"Y-m-d H:i:s","Y-m-d"|after:yesterday' ,
            'use_end_time' =>[
                'required',
                'date_format:"Y-m-d H:i:s',
                "after:".$params['use_begin_time'],
            ],
            'min_limit' => 'required|numeric|min:0',
            'price' => 'required|numeric|min:0',
            'total_num' => 'required|integer|min:-1',
            'use_type' => 'required|integer|min:1|max:2',
            'use_product_type' => 'required|integer|min:1|max:2',
            'single_num' => 'required|integer|min:1',
            'product_list' => [
                Rule::requiredIf($params['use_type']==2),
            ],
            'product_list.*' => [
                'required','integer','min:1',
                Rule::exists('fly_product','id')
                    ->where('check_status','1')
                    ->where('is_show','1')
                    ->where('type',$params['use_product_type'])
            ],
        ];
        $checkVal = [
            'use_begin_time.required' => '请填写使用开始时间',
            'use_begin_time.date_format' => '使用开始时间格式不对',
            'use_begin_time.after' => '使用开始时间至少从今天开始',
            'use_end_time.required' => '请填写使用结束时间',
            'use_end_time.date_format' => '使用结束时间格式不对',
            'use_end_time.after' => '使用结束时间至少大于开始时间',

            'min_limit.required' => '满xx减额度必填',
            'min_limit.numeric' => '满xx为数字',
            'min_limit.min' => '限定满减不能小于0',

            'price.required' => '面额必填',
            'price.numeric' => '面额为数字',
            'price.min' => '面额不能小于0',

            'total_num.required' => '总数量必填',
            'total_num.integer' => '总数量整数数字',
            'total_num.min' => '总数量不能小于-1',

            'use_type.required' => '总数量不能小于0',
            'product_list.required' => '商品数组必填',
            'product_list.*.required' => '商品id必填',
            'product_list.*.integer' => '商品id数字',

        ];
        $this->validation($params,$checkKey,$checkVal);
        Db::beginTransaction();
        try{
            $params['created_at'] = Common::date_time(2);
            $params['create_by'] =  parent::getAdminId();
           $res =  $this->FlyCouponService->coupon_insert($params,intval($shop->id));
            if($res){
                Db::commit();
                return $this->jsonResponse->success([],'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败');
            }
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->jsonResponse->error($e->getCode(),$e->getMessage());
        }
    }

    public function edit()
    {
        $params = $this->request->all();
        $checkKey= [
            'id' => 'required|integer|min:0|exists:fly_coupon',
            'use_begin_time' => 'required|date_format:"Y-m-d H:i:s","Y-m-d"|after:yesterday' ,
            'use_end_time' =>[
                'required',
                'date_format:"Y-m-d H:i:s',
                "after:".$params['use_begin_time'],
            ],
            'min_limit' => 'required|numeric|min:0',
            'price' => 'required|numeric|min:0',
            'total_num' => 'required|integer|min:0',
            'single_num' => 'required|integer|min:1',
        ];
        $checkVal = [
            'id.required' => '优惠券ID不能为空',
            'id.integer' => '优惠券Id为整数数字',
            'id.min' => '优惠券Id不能为负数',
            'id.exists' => '优惠券不存在或已删除',

            'use_begin_time.required' => '请填写使用开始时间',
            'use_begin_time.date_format' => '使用开始时间格式不对',
            'use_end_time.required' => '请填写结束时间',
            'use_end_time.date_format' => '结束时间格式不对',

            'min_limit.required' => '满xx减额度必填',
            'min_limit.numeric' => '满xx为数字',
            'min_limit.min' => '限定满减不能小于-1',

            'price.required' => '面额必填',
            'price.numeric' => '面额为数字',
            'price.min' => '面额不能小于0',

            'total_num.required' => '总数量必填',
            'total_num.integer' => '总数量整数数字',
            'total_num.min' => '总数量不能小于0',
        ];
        $this->validation($params,$checkKey,$checkVal);
        Db::beginTransaction();
        try{
            $params['updated_at'] = date('Y-m-d H:i:s');
            $params['update_by'] = parent::getAdminId();
            $res =  $this->FlyCouponService->coupon_update($params);
            if($res){
                Db::commit();
                return $this->jsonResponse->success([],'修改成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
            }
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->jsonResponse->error($e->getCode(),$e->getMessage());
        }
    }

    public function detail()
    {
        $id= $this->request->input('id');
        $this->validation(
            ['id'=>$id],
            [
                'id' => 'required|integer|min:0|exists:fly_coupon',
            ],
            [
                'id.required' => '优惠券ID不能为空',
                'id.integer' => '优惠券Id为整数数字',
                'id.min' => '优惠券Id不能为负数',
                'id.exists' => '优惠券不存在或已删除',
            ]
        );

        return $this->jsonResponse->success($this->FlyCouponService->get_coupon_info(intval($id)),'优惠券详情');
    }

//    商铺删除接口
    public function del()
    {
        $params = $this->request->all();
        $this->validation(
            $params,
            [
                'id' => [
                    'required',
                    'integer',
                    'min:0',
                    'exists:fly_coupon',
                ]
            ],
            [
                'id.required' => '优惠券ID不能为空',
                'id.integer' => '优惠券Id为整数数字',
                'id.min' => '优惠券Id不能为负数',
                'id.exists' => '优惠券不存在或已删除',
            ]
        );
        Db::beginTransaction();
        try{
          $res =  $this->FlyCouponService->deleteByUser([$params['id']],$this->getAdminId());
            if($res){
                Db::commit();
                return $this->jsonResponse->success([],'删除成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除重置失败');
            }
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,$e->getMessage());
        }
    }

}
